package com.shunwang.errors.engine.builder.xml;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import com.shunwang.errors.engine.builder.LoggerParser;
import com.shunwang.errors.engine.builder.bean.NodeBean;
import com.shunwang.errors.engine.builder.bean.NodeBeans;
import com.shunwang.errors.engine.builder.bean.NodeMethod;
import com.shunwang.errors.engine.core.ErrorsHandler;
import com.shunwang.errors.engine.core.Mapper;
import com.shunwang.errors.engine.core.Mapping;
import com.shunwang.errors.engine.handler.Handler;
import com.shunwang.errors.engine.util.ClazzUtil;
import com.shunwang.errors.exception.ParserException;

public class LoggerXmlParser extends LoggerParser{	

	private InputStream is;
	
	public LoggerXmlParser(InputStream is){
		this.is = is;
	}
	
	public void addNodeList(NodeBeans node){
		nodeBeans = node;
	}
	public ErrorsHandler parser() throws Exception{
		parserData();
		return buildLoggerHandler();
	}

	public void parserData() throws IOException,ParserException{
		try {
			Digester digester = createStartDigester();
			digester.push(this);
			digester.parse(is);
		} catch (SAXException e) {
			throw new ParserException(e);
		}
	}
	
	protected Digester createStartDigester() {
		Digester digester = new Digester();
		digester.setValidating(false);
        digester.setClassLoader(LoggerXmlParser.class.getClassLoader());
        
        digester.addObjectCreate("beans", NodeBeans.class);
	        digester.addObjectCreate("beans/bean",NodeBean.class);
	        digester.addSetProperties("beans/bean");
		        digester.addObjectCreate("beans/bean/method",NodeMethod.class);
		        digester.addSetProperties("beans/bean/method");
			        digester.addSetProperties("beans/bean/method/handler");
			        digester.addObjectCreate("beans/bean/method/exception",ArrayList.class);
				        digester.addObjectCreate("beans/bean/method/exception/value", StringBuffer.class);
				        digester.addCallMethod("beans/bean/method/exception/value", "append", 1);
				        digester.addCallParam("beans/bean/method/exception/value", 0);
				        digester.addSetNext("beans/bean/method/exception/value", "add");
			        digester.addSetNext("beans/bean/method/exception","setExClazz");
		        digester.addSetNext("beans/bean/method","setMethod");
	        digester.addSetNext("beans/bean","setList");
	    digester.addSetNext("beans", "addNodeList");
        return digester;
	}
}
